package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.*;
import com.jackrain.nea.core.redis.CusRedisTemplate;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.OmsDLTranOutSaveCmd;
import com.jackrain.nea.fc.dl.api.OmsDlRetailSaveCmd;
import com.jackrain.nea.fc.dl.mapper.OmsDlRetailSaveMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.RedisOpsUtil;
import com.jackrain.nea.util.ReferenceUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class OmsDlRetailSaveCmdImpl extends CommandAdapter implements OmsDlRetailSaveCmd {
    @Autowired
    PostDubbleEvent postDubbleEvent;
    @Autowired
    PostHandleEvent postHandleEvent;
    @Autowired
    private QueryUserUtil queryUserUtil;
    @Autowired
    QueryCpUtil queryCpUtil;
    @Reference(version = "1.0", group = "cp")
    private OmsDLTranOutSaveCmd OmsDLTranOutSaveCmd;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {
        log.debug("OmsDlRetailSaveCmdImpl--map-->{}", map);

        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"),
                "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
//        log.debug("OmsDlRetailSaveCmdImpl--param-->{}",param);

        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！" + map);
        }

        OmsDlRetailSaveMapper omsDlRetailSaveMapper = ApplicationContextHandle.getBean(OmsDlRetailSaveMapper.class);
        CusRedisTemplate<String, String> redisTemplate = RedisOpsUtil.getStrRedisTemplate();
        JSONArray paramArray = param.getJSONArray("data");
        JSONArray errorArray = new JSONArray();
        JSONArray spendTimeArray = new JSONArray();
        List succIdList = new ArrayList();

        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject errorJson = new JSONObject();
            JSONObject tranJson = paramArray.getJSONObject(i);
            JSONObject zbJS = tranJson.getJSONObject("DL_T_RETAIL_TRANSFER");
            String bill_No = zbJS.getString("BILL_NO");
            String type = zbJS.getString("TYPE");
            zbJS.remove("TYPE");
            String tranOutFromBillNo = "omstranoutfrombillno:" + bill_No;

            try {
                String storeEcode = zbJS.getString("CP_C_STORE_ECODE");
                JSONObject whereJs = new JSONObject();
                whereJs.put("ECODE", storeEcode);
                JSONObject storeInfo = queryCpUtil.queryCP("CP_C_STORE", "RETAIL_STORE_ECODE", whereJs);
                if (storeInfo != null && storeInfo.size() > 0) {
                    String retailStoreEcode = storeInfo.getString("RETAIL_STORE_ECODE");
                    zbJS.put("CP_C_STORE_ECODE", retailStoreEcode);

                    //如果是零售单，并且发货仓库不等于零售门店 生成调拨出库单 "0".equals(type) && !storeEcode.equals(retailStoreEcode)
                    if ("0".equals(type) && !storeEcode.equals(retailStoreEcode)) {
                        //根据已有的字段 封装出调拨单所需字段
                        JSONArray resultArray = null;
                        String value = String.valueOf(redisTemplate.opsForValue().get(tranOutFromBillNo));
//                        log.debug("redis中查询单号：" + value);

                        //判断 原单号在redis中是否存在 如果存在就不再调用调拨单的逻辑
                        if (bill_No.equals(value)) {
                            log.debug("该单号在redis中已存在" + bill_No);
                            log.error("retailcreatetranout fail billno:" + bill_No);
                            errorJson.put("error", "该单号在redis中已存在");
                            errorJson.put("BILL_NO", bill_No);
                            errorArray.add(errorJson);
                        } else {
                            //将单号存放到redis
                            redisTemplate.opsForValue().set(tranOutFromBillNo, bill_No, 24, TimeUnit.HOURS);

                            resultArray = tranOutDataTrim(tranJson, storeEcode);
                            JSONObject paramJson = new JSONObject();
                            paramJson.put("data", resultArray);
                            HashMap map1 = new HashMap();
                            map1.put("param", paramJson);
                            accesLogger.info("OmsDlRetailSaveCmdImpl--paramJson-->{}", paramJson);

                            Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(),
                                    "com.jackrain.nea.fc.dl.api.OmsDLTranOutSaveCmd",
                                    "cp", "1.0");
                            ValueHolder result = ((OmsDLTranOutSaveCmd) o).execute(map1);
                            accesLogger.info("OmsDlRetailSaveCmdImpl--result-->{}", result);

                            if (result == null) {
                                errorJson.put("error", "调用生成调拨单服务错误：返回为空");
                                errorJson.put("BILL_NO", bill_No);
                                errorArray.add(errorJson);
                                //异常时 删除redis,便于数据重试
//                                redisTemplate.delete(tranOutFromBillNo);
                            } else {
                                if ("-1".equals(result.get("code"))) {
                                    errorJson.put("error", "调用生成调拨单服务错误：code=-1");
                                    errorJson.put("BILL_NO", bill_No);
                                    errorArray.add(errorJson);
//                                    redisTemplate.delete(tranOutFromBillNo);
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                String error = "";
                if ((e instanceof NDSException)) {
                    error = e.getMessage();
                } else {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    error = sw.toString();
                }
//                log.debug("生成调拨单失败" + error);
                log.error("OmsDlRetailSaveCmdImpl-createtranout-error-->" + bill_No + "{}", e);
                errorJson.put("BILL_NO", bill_No);
                errorJson.put("message", "生成调拨单失败" + error);
                errorArray.add(errorJson);
//                redisTemplate.delete(tranOutFromBillNo);
            }

            try {
                JSONObject spendTime = new JSONObject();
                int statu = 0;
                Long retObjid = null;
                int count = omsDlRetailSaveMapper.selectReatilCount(bill_No);
                if (count != 0) {
                    statu = statu + 1;
                }

                //保存用户
                String saveUserName = zbJS.getString("OWNERNAME");
                User saveUser = queryUserUtil.getUser(saveUserName);
                //收银用户
                String statusName = zbJS.getString("STATUSNAME");
                User statusUser = queryUserUtil.getUser(statusName);
                //记账用户
                String accountUserName = zbJS.getString("OPR_ECODE");
                User accountUser = queryUserUtil.getUser(accountUserName);

                //save
                String noticSave = "com.jackrain.nea.retail.api.DlRetailSaveCmd:1.0:pos";
                //收银
                String noticCharge = "com.jackrain.nea.retail.api.DlRetailChargeCmd:1.0:pos";
                //记帐
                String noticAccount = "com.jackrain.nea.retail.api.DlRetailAccountCmd:1.0:pos";

                //0,初始状态（未保存）  1，已保存   2，已收银
                if (0 == statu) {
                    long saveStartTime = System.currentTimeMillis();
                    QuerySessionImpl querySession = new QuerySessionImpl(saveUser);
                    DefaultWebEvent event = new DefaultWebEvent("dlRetail", new HashMap(16));

                    JSONObject resultJson = retailSaveData(tranJson, omsDlRetailSaveMapper);
                    event.put("param", resultJson);
                    querySession.setEvent(event);
                    accesLogger.info("OmsDlRetailSaveCmdImpl--resultJson-->{}", resultJson);

                    JSONObject retJo = postDubbleEvent.executePostDubble(noticSave, querySession);
                    double saveEndTime = (double) (System.currentTimeMillis() - saveStartTime) / 1000.0D;
                    spendTime.put("saveTime", saveEndTime);
                    spendTime.put("saveRetData", retJo);
//                    log.debug("saveTime->" + saveEndTime);
//                    log.debug("DlRetailSave_retJo->" + retJo);
                    accesLogger.info("OmsDlRetailSaveCmdImpl--retJo-->{}", retJo);

                    if (retJo.containsKey("code") && (int) retJo.get("code") != 0) {
                        errorJson.put("BILL_NO", bill_No);
                        if (null == retJo.get("message")) {
                            errorJson.put("message", "调用标准零售保存服务异常");
                        } else {
                            errorJson.put("message", "零售保存服务异常:" + retJo.get("message") +
                                    " retData->" + retJo.get("data"));
                        }
                        errorArray.add(errorJson);
                        continue;
                    }
                    JSONObject retData = retJo.getJSONObject("data");
                    retObjid = retData.getLong("objid");
                } else {
                    retObjid = omsDlRetailSaveMapper.selectObjidByBillNo(zbJS.getString("BILL_NO"));
                }

                long chargeStartTime = System.currentTimeMillis();
                QuerySessionImpl chargeQuerySession = new QuerySessionImpl(statusUser);
                DefaultWebEvent event = new DefaultWebEvent("dlRetail", new HashMap(16));
                JSONObject chargeJson = retailChargeData(retObjid);
                chargeJson.put("STATUSTIME", zbJS.getString("STATUSTIME"));
//                log.info("charge_resultJson==>" + chargeJson.toString());
                accesLogger.info("OmsDlRetailSaveCmdImpl--chargeJson-->{}", chargeJson);

                event.put("param", chargeJson);
                event.setParameter("command", noticCharge);
                event.setParameter("table", "DL_B_RETAIL");
                event.setParameter("webaction", "OBJECT_RETAIL_CHARGE");
                chargeQuerySession.setEvent(event);

                //handle调用收银
                JSONObject retChargeJo = postHandleEvent.executePostHandle(chargeJson, chargeQuerySession, event, "webaction");
                double chargeEndTime = (double) (System.currentTimeMillis() - chargeStartTime) / 1000.0D;
                spendTime.put("chargeTime", chargeEndTime);
                spendTime.put("chargeRetData", retChargeJo);
//                log.debug("chargeTime->" + chargeEndTime);
//                log.debug("DlRetailChargeCmd_handle_retJo->" + retChargeJo);
                accesLogger.info("OmsDlRetailSaveCmdImpl--retChargeJo-->{}", retChargeJo);

                if (retChargeJo.containsKey("code") && (int) retChargeJo.get("code") != 0) {
                    errorJson.put("BILL_NO", bill_No);
                    if (null == retChargeJo.get("message")) {
                        errorJson.put("message", "调用标准零售收银服务异常");
                    } else {
                        errorJson.put("message", "零售收银服务异常:" + retChargeJo.get("message"));
                    }
                    errorArray.add(errorJson);
                    continue;
                }
                chargeJson.remove("STATUSTIME");

                //调用记账
                long accountStartTime = System.currentTimeMillis();
                QuerySessionImpl accountQuerySession = new QuerySessionImpl(accountUser);
                DefaultWebEvent accountevent = new DefaultWebEvent("dlRetail", new HashMap(16));
                JSONObject accountJson = retailChargeData(retObjid);

                accountevent.put("param", accountJson);
                accountevent.setParameter("command", noticAccount);
                accountevent.setParameter("webaction", "OBJECT_RETAIL_ACCOUNT");
                accountevent.setParameter("isSendMq", "Y");
                accountQuerySession.setEvent(accountevent);
                accesLogger.info("OmsDlRetailSaveCmdImpl--accountJson-->{}", accountJson);
//                log.info("account_resultJson==>" + accountJson.toString());
                //调用记账服务
                JSONObject retAccountJo = postHandleEvent.executePostHandle(accountJson, accountQuerySession, accountevent, "webaction");
                double accountEndTime = (double) (System.currentTimeMillis() - accountStartTime) / 1000.0D;
                spendTime.put("accountTime", accountEndTime);
                spendTime.put("accountRetData", retAccountJo);
//                log.debug("accountTime->" + accountEndTime);
//                log.info("DlRetailAccountCmd_retJo->" + retAccountJo);
                accesLogger.info("OmsDlRetailSaveCmdImpl--retAccountJo-->{}", retAccountJo);

                if (retAccountJo.containsKey("code") && (int) retAccountJo.get("code") != 0) {
                    errorJson.put("BILL_NO", bill_No);
                    if (null == retAccountJo.get("message")) {
                        errorJson.put("message", "调用标准记账收银服务异常");
                    } else {
                        errorJson.put("message", "零售记账服务异常:" + retAccountJo.get("message"));
                    }
                    errorArray.add(errorJson);
                    continue;
                }
                spendTimeArray.add(spendTime);

            } catch (Exception e) {
                String error = "";
                if ((e instanceof NDSException)) {
                    error = e.getMessage();
                } else {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    error = sw.toString();
                }
                errorJson.put("BILL_NO", bill_No);
                errorJson.put("message", error);
                errorArray.add(errorJson);
            }
        }

        if (errorArray.size() > 0) {
            vh.put("error", errorArray);
            vh.put("code", -1);
        } else {
            vh.put("code", 0);
        }
        vh.put("successIds", StringUtils.collectionToDelimitedString(succIdList, ","));
        vh.put("spendTime", spendTimeArray);
        vh.put("retStr", errorArray);
        return vh;
    }

    public JSONArray tranOutDataTrim(JSONObject tranJson, String storeEcode) throws Exception {

//        log.debug("调拨参数生成" + tranJson + storeEcode);
        JSONArray resultArray = new JSONArray();
        JSONObject oldJson = tranJson.getJSONObject("DL_T_RETAIL_TRANSFER");
        JSONObject zbJs = new JSONObject();
        JSONObject dlJson = new JSONObject();
        JSONArray itemArray = new JSONArray();
        int ifSetDisplay = oldJson.getIntValue("IF_SET_DISPLAY");
        if (1 == ifSetDisplay) {
            //陈列设零
            dlJson.put("IF_SET_DISPLAY", "Y");
        } else {
            dlJson.put("IF_SET_DISPLAY", "N");
        }

        //是否跨区域配销中心
        dlJson.put("VARCHAR3", "N");
        //是否店到店
        dlJson.put("VARCHAR4", "N");
        //单据日期
        dlJson.put("BILL_DATE", oldJson.getString("BILL_DATE").replace("-", "").substring(0, 8));
        //库存日期
        dlJson.put("STORE_DATE", oldJson.getString("BILL_DATE").replace("-", "").substring(0, 8));
        //发货店仓编码
        dlJson.put("CP_C_ORIG_ECODE", storeEcode);
        //收货店仓编码
        dlJson.put("CP_C_DEST_ECODE", oldJson.getString("CP_C_STORE_ECODE"));
        //调拨类型 特殊
        dlJson.put("TRAN_TYPE", 5);
        //调拨性质 一般
        dlJson.put("TRAN_FLAG", 0);
        //发货类型 直接调拨
        dlJson.put("ORIG_TYPE", 3);
        //原单号编码
        dlJson.put("FROM_BILL_NO", oldJson.getString("BILL_NO"));
//        //补货周期
//        dlJson.put("CYCLE_DAYS", oldJson.getInteger("CYCLE_DAYS"));
//        //退货周期
//        dlJson.put("CYCLE_DAYS_RET", oldJson.getInteger("CYCLE_DAYS_RET"));
        //特殊单计入库存日期
        dlJson.put("SP_STOCK_DATE", oldJson.getString("BILL_DATE").replace("-", "").substring(0, 8));
        //备注
//        dlJson.put("REMARK", "由WING订单发货产生");
//        //是否云仓生成
//        dlJson.put("IS_CLOUD_ORDER", oldJson.get("IS_CLOUD_ORDER"));
        //零售单号
        dlJson.put("DL_B_RETAIL_NO", oldJson.get("BILL_NO"));
//        //加补类型
//        dlJson.put("ADD_TYPE_ID", oldJson.get("ADD_TYPE"));
//        //中间表ID集合
//        dlJson.put("IDLIST", oldJson.getString("IDLIST"));
        //用户名
        dlJson.put("OPR_ECODE", "INTER99999");
        //自动审核
        dlJson.put("AUTO_CHECK", 1);
        //自动发出
        dlJson.put("AUTO_SEND", 1);
        //自动验收
        dlJson.put("AUTO_ACCEPT", 1);

        JSONArray listArray = tranJson.getJSONArray("DL_T_RETAIL_ITEM_TRANSFER");
        for (int j = 0; j < listArray.size(); j++) {
            JSONObject oldItem = listArray.getJSONObject(j);

            JSONObject itemjo = new JSONObject();
            //吊牌价
            itemjo.put("PRICE_LIST", oldItem.getBigDecimal("PRICE_LIST"));
            //是否缓冲生成
            itemjo.put("IS_BF_SUPPLY", 1);
            //调拨数量
            itemjo.put("QTY_BILL", oldItem.getBigDecimal("QTY_BILL"));
            //调拨金额
            itemjo.put("AMT_BILL", oldItem.getBigDecimal("PRICE_LIST").multiply(oldItem.getBigDecimal("QTY_BILL")));
            //条码编码
            itemjo.put("PS_C_SKU_ECODE", oldItem.get("PS_C_SKU_ECODE"));
//            //备注
//            itemjo.put("REMARK", oldItem.getString("REMARK"));
            itemArray.add(itemjo);
        }

        zbJs.put("DL_T_TRAN_TRANSFER", dlJson);
        zbJs.put("DL_T_TRAN_ITEM_TRANSFER", itemArray);
        resultArray.add(zbJs);
//        log.info("数据转换完成" + resultArray);
        return resultArray;
    }


    public JSONObject retailChargeData(Long retObjid) throws Exception {
        JSONObject chargeJson = new JSONObject();
        JSONObject subParam = new JSONObject();
        subParam.put("idArr", new JSONArray());
        subParam.put("table", "DL_B_RETAIL_ITEM");
        chargeJson.put("objid", retObjid);
        chargeJson.put("IS_F4CHECK", "N");
        chargeJson.put("table", "DL_B_RETAIL");
        chargeJson.put("subParam", subParam);
        return chargeJson;
    }

    public JSONObject retailSaveData(JSONObject tranJson, OmsDlRetailSaveMapper omsDlRetailSaveMapper) throws
            Exception {

        JSONObject zbJS = tranJson.getJSONObject("DL_T_RETAIL_TRANSFER");
        JSONArray itemJS = tranJson.getJSONArray("DL_T_RETAIL_ITEM_TRANSFER");
        JSONArray payitemJS = tranJson.getJSONArray("DL_T_RETAIL_PAY_TRANSFER");

        /*************处理明细表数据************/
        for (int j = 0; j < itemJS.size(); j++) {
            JSONObject itemJson = itemJS.getJSONObject(j);
            itemJson.put("ID", -1);
            itemJson.put("ISACTIVE", "Y");

            //商品ID
            if (null != itemJson.getString("PS_C_SKU_ECODE")) {
                String skuEcode = itemJson.getString("PS_C_SKU_ECODE");
                //跨库查询
                JSONObject whereJs = new JSONObject();
                whereJs.put("ECODE", skuEcode);
                whereJs.put("CP_C_DISTRIB_ID", 0);
                JSONObject h = queryCpUtil.queryCP("PS_C_SKU",
                        "PS_C_PRO_ID,PS_C_SPEC1OBJ_ID,PS_C_SPEC2OBJ_ID,ID", whereJs);

                if (null != h) {
                    //条码ID && h.size() > 0
                    itemJson.put("PS_C_SKU_ID", h.get("ID"));

                    if (null != h.get("PS_C_SPEC1OBJ_ID")) {
                        //颜色ID
                        itemJson.put("PS_C_CLR_ID", h.get("PS_C_SPEC1OBJ_ID"));
                        //跨库查询
                        JSONObject whereSpecObj = new JSONObject();
                        whereSpecObj.put("ID", h.get("PS_C_SPEC1OBJ_ID"));
                        JSONObject specobj = queryCpUtil.queryCP("PS_C_SPECOBJ",
                                "ENAME,ECODE", whereSpecObj);
                        //颜色编码
                        itemJson.put("PS_C_CLR_ECODE", specobj.get("ECODE"));
                        //颜色名称
                        itemJson.put("PS_C_CLR_ENAME", specobj.get("ENAME"));
                    }

                    if (null != h.get("PS_C_SPEC2OBJ_ID")) {
                        //尺寸ID
                        itemJson.put("PS_C_SIZE_ID", h.get("PS_C_SPEC2OBJ_ID"));
                        //跨库查询
                        JSONObject whereSpecObj = new JSONObject();
                        whereSpecObj.put("ID", h.get("PS_C_SPEC2OBJ_ID"));
                        JSONObject specobj = queryCpUtil.queryCP("PS_C_SPECOBJ",
                                "ENAME,ECODE", whereSpecObj);
                        //尺寸编码
                        itemJson.put("PS_C_SIZE_ECODE", specobj.get("ECODE"));
                        //尺寸名称
                        itemJson.put("PS_C_SIZE_ENAME", specobj.get("ENAME"));
                    }
                } else {
                    throw new NDSException("SKU 查询为空！  sku编码：" + skuEcode);
                }

                if (null != h.get("PS_C_PRO_ID")) {
                    //商品ID
                    itemJson.put("PS_C_PRO_ID", h.get("PS_C_PRO_ID"));
                    //跨库查询
                    JSONObject whereProJs = new JSONObject();
                    whereProJs.put("ID", h.get("PS_C_PRO_ID"));
                    whereProJs.put("CP_C_DISTRIB_ID", 0);
                    JSONObject proHashMap = queryCpUtil.queryCP("PS_C_PRO",
                            "ECODE,ENAME,NUMDIM26,PROMOTIONTYPE,PRONATURE", whereProJs);

                    if (null != proHashMap && proHashMap.size() > 0) {
                        //款号
                        itemJson.put("PS_C_PRO_ECODE", proHashMap.get("ECODE"));
                        //商品名称
                        itemJson.put("PS_C_PRO_ENAME", proHashMap.get("ENAME"));
                        //品类ID
                        itemJson.put("PRO_TYPE_DEPART_ID", proHashMap.get("NUMDIM26"));
                        Long proMotion = TypeUtils.castToLong(proHashMap.get("PROMOTIONTYPE"));
                        if (null != proMotion) {
                            //跨库查询
                            JSONObject whereProDimJson = new JSONObject();
                            whereProDimJson.put("ID", proMotion);
                            JSONObject proDimHashMap = queryCpUtil.queryCP("PS_C_PRODIM_ITEM",
                                    "ENAME", whereProDimJson);
                            if (null != proDimHashMap && proDimHashMap.size() > 0) {
                                //推广类型
                                itemJson.put("PS_C_PRO_PROMOTIONTYPE", proDimHashMap.get("ENAME"));
                            }
                        }

                        Long pronature = TypeUtils.castToLong(proHashMap.get("PRONATURE"));
                        if (null != pronature) {
                            //跨库查询
                            JSONObject whereProDimJson = new JSONObject();
                            whereProDimJson.put("ID", pronature);
                            JSONObject proDimHashMap = queryCpUtil.queryCP("PS_C_PRODIM_ITEM",
                                    "ENAME", whereProDimJson);
                            if (null != proDimHashMap && proDimHashMap.size() > 0) {
                                //货品性质
                                itemJson.put("PS_C_PRO_PRONATURE", proDimHashMap.get("ENAME"));
                            }
                        }
                    } else {
                        throw new NDSException("商品档案 查询为空！  商品ID：" + h.get("PS_C_PRO_ID"));
                    }
                }
            }

            if (itemJson.containsKey("PRO_TYPE_DEPART_ID") &&
                    (null != itemJson.getLong("PRO_TYPE_DEPART_ID"))) {
                //跨库查询
                JSONObject whereProDimJs = new JSONObject();
                whereProDimJs.put("ID", itemJson.getLong("PRO_TYPE_DEPART_ID"));
                JSONObject proDimHashMap = queryCpUtil.queryCP("PS_C_PRODIM_ITEM",
                        "ECODE,ENAME", whereProDimJs);
                if (null != proDimHashMap && proDimHashMap.size() > 0) {
                    //品类编码
                    itemJson.put("PRO_TYPE_DEPART_ECODE", proDimHashMap.get("ECODE"));
                    //品类名称
                    itemJson.put("PRO_TYPE_DEPART_ENAME", proDimHashMap.get("ENAME"));
                }
            }

            String empecode = itemJson.getString("CP_C_SALER_ECODE");
            if (null != empecode) {
                //跨库查询
                JSONObject whereEmp = new JSONObject();
                whereEmp.put("ECODE", empecode);
                JSONObject empHashMap = queryCpUtil.queryCP("CP_C_EMP",
                        "ENAME,ID", whereEmp);
                if (null != empHashMap && empHashMap.size() > 0) {
                    //营业员ID
                    itemJson.put("CP_C_SALER_ID", empHashMap.get("ID"));
                    //营业员姓名
                    itemJson.put("CP_C_SALER_ENAME", empHashMap.get("ENAME"));
                }
            }
        }

        for (int j = 0; j < payitemJS.size(); j++) {
            JSONObject payitemJson = payitemJS.getJSONObject(j);
            payitemJson.put("ID", -1);
            payitemJson.put("ISACTIVE", "Y");

            String payEcode = payitemJson.getString("PAY_WAY_CODE");
            if (null == payEcode) {
                throw new NDSException("付款方式编码不能为空!");
            } else {
                HashMap wayHash = omsDlRetailSaveMapper.selPaymentID(payEcode);
                if (null != wayHash) {
                    if (null == wayHash || wayHash.size() <= 0) {
                        throw new NDSException("付款方式查询为空!  payEcode:" + payEcode);
                    }
                    //付款方式ID
                    payitemJson.put("PAY_WAY_ID", wayHash.get("ID"));
                    //付款方式名称
                    payitemJson.put("PAY_WAY_NAME", wayHash.get("ENAME"));
                    if ("3".equals(payEcode)) {
                        payitemJson.put("COUPON_NO", payitemJson.getString("PAY_NO"));
                        payitemJson.put("PAY_NO", null);
                    }
                }
            }
        }

        /*************处理主表数据************/
        JSONObject newzbJson = new JSONObject();
        Set<String> keySet = zbJS.keySet();
        for (String key : keySet) {
            if ("OPR_ECODE".equals(key) || "IDLIST".equals(key) || "AUTO_CHARGE".equals(key)) {
                continue;
            } else {
                newzbJson.put(key, zbJS.get(key));
            }
        }
        newzbJson.remove("CREATIONDATE");
        newzbJson.put("ISACTIVE", "Y");
        newzbJson.put("SALE_TYPE", null);
//        newzbJson.put("BILL_ADD_TYPE", 2);
        newzbJson.put("PAY_CHANGE", 0);
        newzbJson.remove("STATUSNAME");
        newzbJson.remove("STATUSTIME");
        String retail = zbJS.getString("RETAIL_TYPE");
        if ("POS".equals(retail)) {
            newzbJson.put("RETAIL_TYPE", 1);
        } else {
            newzbJson.put("RETAIL_TYPE", 0);
        }

        if (zbJS.containsKey("CP_C_STORE_ECODE") && (null != zbJS.getString("CP_C_STORE_ECODE"))) {
            String ecode = zbJS.getString("CP_C_STORE_ECODE");
            JSONObject whereJs = new JSONObject();
            whereJs.put("ECODE", ecode);
            //跨库查询
            JSONObject h = queryCpUtil.queryCP("CP_C_STORE", "ID", whereJs);
            if (null != h && h.size() > 0) {
                //门店ID
                newzbJson.put("CP_C_STORE_ID", h.get("ID"));
            } else {
                throw new NDSException("店仓 查询为空   店仓编码:" + ecode);
            }
        }

        String saveUserName = zbJS.getString("OWNERNAME");
        User user = queryUserUtil.getUser(saveUserName);
        if (zbJS.containsKey("VP_C_VIP_ECODE") && (null != zbJS.getString("VP_C_VIP_ECODE"))) {
            String ecode = zbJS.getString("VP_C_VIP_ECODE");
            DefaultWebEvent event = new DefaultWebEvent("test", new HashMap(16));
            QuerySessionImpl querySession = new QuerySessionImpl(user);
            //查询VIP档案ID
            JSONObject vipSearchJson = new JSONObject();
            //fixedcolumns
            JSONObject fixedcolumnsJson = new JSONObject();
            fixedcolumnsJson.put("ACC.ECODES", ecode);

            JSONArray searchTypeArray = new JSONArray();
            JSONObject ecodeName = new JSONObject();
            ecodeName.put("name", "ACC.ECODES");
            ecodeName.put("type", "exact");
            searchTypeArray.add(ecodeName);

            vipSearchJson.put("fixedcolumns", fixedcolumnsJson);
            vipSearchJson.put("searchtype", searchTypeArray);
            event.put("param", vipSearchJson);
            querySession.setEvent(event);
            String vipnotic = "com.jackrain.nea.vp.api.CvipSearchCmd:1.0:vp";
            JSONObject vipeRetJson = postDubbleEvent.executePostDubble(vipnotic, querySession);

//            log.info("vipeRetJson:" + vipeRetJson);
            if (null == vipeRetJson || (!vipeRetJson.containsKey("IDS"))) {
//                throw new NDSException("未查询到VIPID   " + vipeRetJson);
                newzbJson.put("VP_C_VIP_ACC_ID", null);
            }

            JSONArray idsArray = vipeRetJson.getJSONArray("IDS");
            if (null == idsArray || idsArray.size() <= 0) {
//                throw new NDSException("未查询到VIPID   ecode:" + ecode);
                newzbJson.put("VP_C_VIP_ACC_ID", null);
            } else {
                Long vipID = idsArray.getLong(0);
                //账户ID
                newzbJson.put("VP_C_VIP_ACC_ID", vipID);
            }
        }

        newzbJson.put("STATUS", 1);

        //调用vp接口，根据淘宝名查询会员卡号
        if (zbJS.containsKey("BUYERNICK") && (null != zbJS.getString("BUYERNICK"))) {
            if (!"".equals(zbJS.getString("BUYERNICK"))) {
                DefaultWebEvent event = new DefaultWebEvent("test", new HashMap(16));
                QuerySessionImpl querySession = new QuerySessionImpl(user);
                JSONObject vipSearchJson = new JSONObject();
                vipSearchJson.put("TAOBAO_ENAME", zbJS.getString("BUYERNICK"));

                HashMap fixcolumn1 = new HashMap();
                fixcolumn1.put("param", vipSearchJson);

                event.put("param", fixcolumn1);
                querySession.setEvent(event);
                String query_vip_cardno_notic = "com.jackrain.nea.vp.api.CvipGetCardNoCmd:1.0:vp";
                log.debug("OmsDlRetailSaveCmdImpl-queryvipcode-param--->{}", vipSearchJson);
                try {
                    JSONObject vipeRetJson = postDubbleEvent.executePostDubbleToMap(query_vip_cardno_notic, querySession);
                    log.debug("OmsDlRetailSaveCmdImpl-queryvipcode-return--->{}", vipeRetJson);
                    if (null != vipeRetJson && vipeRetJson.containsKey("data")) {
                        JSONArray vip_cardno_array = vipeRetJson.getJSONArray("data");
                        if (vip_cardno_array != null && vip_cardno_array.size() > 0) {
                            JSONObject vip_card_json = vip_cardno_array.getJSONObject(0);
                            String vip_cardno = vip_card_json.getString("CARDNO");
                            newzbJson.put("VP_C_VIP_ECODE", vip_cardno);
                        }
                    }
                } catch (Exception e) {
                    log.error("OmsDlRetailSaveCmdImpl-queryvipcode-error--->{}", e);
                }
            }
        }
        newzbJson.remove("BUYERNICK");

        JSONObject fixColumn = new JSONObject();
        fixColumn.put("DL_B_RETAIL", newzbJson);
        fixColumn.put("DL_B_RETAIL_ITEM", itemJS);
        fixColumn.put("DL_B_RETAIL_PAY_ITEM", payitemJS);

        JSONObject resultJson = new JSONObject();
        resultJson.put("objid", -1);
        resultJson.put("IS_F4CHECK", "N");
        resultJson.put("fixcolumn", fixColumn);
        resultJson.put("table", "DL_B_RETAIL");

//        log.info("resultJson==>" + resultJson.toString());
        return resultJson;
    }

}